package com.ruoyi.generator.controller;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.generator.domain.Question;
import com.ruoyi.generator.domain.WorkOrder;
import com.ruoyi.generator.entity.*;
import com.ruoyi.generator.entity.bo.PlanScheduleInfoBO;
import com.ruoyi.generator.entity.vo.WorkOrderVO;
import com.ruoyi.generator.mapper.WorkOrderMapper;
import com.ruoyi.generator.service.AppService;
import com.ruoyi.generator.service.WorkOrderService;
import com.ruoyi.generator.vo.MaintenanceAppVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app")
public class AppController {

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private AppService appService;

    @Autowired
    private WorkOrderService workOrderService;


    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        try {
            String token = loginService.appLogin(loginBody.getUsername(), loginBody.getPassword(), "", "");
            return AjaxResult.success().put(Constants.TOKEN, token).put("userId",loginService.getUsersId(loginBody.getUsername(), loginBody.getPassword(), "", ""));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/addworkorders")
    public AjaxResult createWorkOrder(@RequestBody WorkOrder workOrder) {
        try {
            workOrderMapper.insertWorkOrder(workOrder);
            return AjaxResult.success("Work order created successfully.");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/completeMaintenance")
    public AjaxResult completeMaintenance(@RequestBody WorkOrder workOrder) {
        try {
            workOrderMapper.insertWorkOrder(workOrder);
            return AjaxResult.success("Work order created successfully.");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PutMapping("/workorders/{id}")
    public AjaxResult updateWorkOrder(@PathVariable Long id, @RequestBody WorkOrderVO workOrder) {
        try {
            workOrder.setId(id.toString());
            workOrder.setIsHandle("1");
            workOrder.setRemark("已解决");
            workOrderMapper.updateWsWorkOrder(workOrder);
            return AjaxResult.success("Work order updated successfully.");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/workordersd/{id}")
    public AjaxResult deleteWorkOrder(@PathVariable Long id) {
        try {
            workOrderMapper.deleteWorkOrderById(id);
            return AjaxResult.success("Work order deleted successfully.");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/workorders/{id}")
    public AjaxResult getWorkOrderById(@PathVariable Long id) {
        try {
            WorkOrder workOrder = workOrderMapper.selectWorkOrderById(id);
            return AjaxResult.success(workOrder);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/workorders")
    public AjaxResult getAllWorkOrders() {
        try {
            List<WorkOrder> workOrders = workOrderMapper.selectAllWorkOrders();
            List<WorkOrder> faultWorkOrders = workOrders.stream()
                    .filter(wo -> "fault".equals(wo.getType()))
                    .collect(Collectors.toList());
            List<WorkOrder> planWorkOrders = workOrders.stream()
                    .filter(wo -> "plan".equals(wo.getType()))
                    .collect(Collectors.toList());
//            List<WorkOrder> preventWorkOrders = workOrders.stream()
//                    .filter(wo -> "prevent".equals(wo.getType()))
//                    .collect(Collectors.toList());
//            List<List<WorkOrder>> result = Arrays.asList(faultWorkOrders, planWorkOrders, preventWorkOrders);
            List<List<WorkOrder>> result = Arrays.asList(faultWorkOrders, planWorkOrders);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/wsworkorders")
    public AjaxResult getAllWsWorkOrders() {
        ClUser cl=new ClUser();
        try {
            List<WorkOrderVO> workOrders = workOrderMapper.selectAllWushuiWorkOrders(cl);
            //进行中
            List<WorkOrderVO> faultWorkOrders = workOrders.stream()
                    .filter(wo -> "fault".equals(wo.getType()))
                    .collect(Collectors.toList());
            //已完成
            List<WorkOrderVO> planWorkOrders = workOrders.stream()
                    .filter(wo -> "plan".equals(wo.getType()))
                    .collect(Collectors.toList());
            //已过期
            List<WorkOrderVO> preventWorkOrders = workOrders.stream()
                    .filter(wo -> "prevent".equals(wo.getType()))
                    .collect(Collectors.toList());
            List<List<WorkOrderVO>> result = Arrays.asList(faultWorkOrders, planWorkOrders, preventWorkOrders);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @GetMapping("/wsworkordersById/{type}/{userId}")
    public AjaxResult getAllWsWorkOrders(@PathVariable String type,@PathVariable String userId) {
        List<WorkOrderVO> workOrders=new ArrayList<WorkOrderVO>();
        ClUser cl=new ClUser();
        cl.setUserId(userId);
        cl=workOrderMapper.getUserDeptinfo(cl);
        workOrders = workOrderMapper.selectAllWushuiWorkOrders(cl);
        try {
             if(type.equals("fault")){
                //进行中
                 workOrders = workOrders.stream()
                        .filter(wo -> "fault".equals(wo.getType()))
                        .collect(Collectors.toList());
            }else if(type.equals("plan")){
                //已完成
                workOrders = workOrders.stream()
                        .filter(wo -> "plan".equals(wo.getType()))
                        .collect(Collectors.toList());
            }else if (type.equals("prevent")){
                //已过期
                workOrders = workOrders.stream()
                        .filter(wo -> "prevent".equals(wo.getType()))
                        .collect(Collectors.toList());
            }
            return AjaxResult.success(workOrders);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /*
   获取提示消息数据
    */
    @GetMapping("/getUserMsgList//{limit}")//获取保养数据    pending未开始  progress进行中    expired 已过期
    public AjaxResult getUserMsgList(@PathVariable Integer limit) {
        List<UserMsg>  UserMsgList  = appService.getMsgList(limit);
        return AjaxResult.success(UserMsgList);
    }

    /**
     * 获取水表数据
     *  type  inflow 进水   outflow 出水
     * */
    @GetMapping("/getWaterData/{type}")//获取保养数据    pending未开始  progress进行中    expired 已过期
    public AjaxResult getWaterData(@PathVariable String type) {
        if ("inflow".equals(type)) {
            ImportWaterQuality importWaterQuality = appService.getImportWaterData();
            return AjaxResult.success(importWaterQuality);
        } else if ("outflow".equals(type)) {
            ImportWaterQuality exportWaterQuality = appService.getExportWaterData();
            return AjaxResult.success(exportWaterQuality);
        } else {
            return AjaxResult.error("Invalid type");
        }
    }

    @GetMapping("/getMaintenanceList/{type}")//获取保养数据    pending未开始  progress进行中    expired 已过期
    public AjaxResult getMaintenanceList(@PathVariable String type) {

        List<MaintenanceAppVO> maintenanceList = appService.getMaintenanceList(type);
        System.out.println(type);
        return AjaxResult.success(maintenanceList);
    }
    @GetMapping("/getAreaList")//获取区域信息
    public AjaxResult getAreaList() {
        List<Area> maintenanceList = appService.getAreaList();
        return AjaxResult.success(maintenanceList);
    }


    @GetMapping("/getClUserList")//获取区域信息
    public AjaxResult getClUserList() {
        List<ClUser> maintenanceList = appService.getClUserList();
        return AjaxResult.success(maintenanceList);
    }
    /**
     * 根据区域ID获取数据（暂返回null）
     * 扫码请求地址：/app/getByArea/{区域id}
     *
     * @param areaId 区域ID
     * @return 暂返回null
     */
    @GetMapping("/getByArea/{areaId}")
    public AjaxResult getByAreaId(@PathVariable String areaId) {
        List<Equipment> equipmentList = appService.getEquipmentByAreaId(String.valueOf(areaId));
        System.out.println("getByArea参数：" + areaId);
        return AjaxResult.success(equipmentList);
    }

    /**
     * app保养提交按钮 修改问题状态
     *
     * @param maintenanceAppVO
     * @return
     */
    @PostMapping("/editMaintenance")
    public AjaxResult editMaintenance(@RequestBody MaintenanceAppVO maintenanceAppVO) {
        int rows = appService.editMaintenance(maintenanceAppVO);
        return AjaxResult.success(rows);
    }

    /**
     * 根据设备编号获取设备检测信息
     *
     * @param planAssociation
     * @return
     */
    @PostMapping("/getEquipmentPlanInfo") // 修改：将@GetMapping改为@PostMapping get请求不应该有请求体 POST请求应该有请求体
    public AjaxResult getEquipmentPlanInfo(@RequestBody PlanAssociation planAssociation) {
        List<PlanScheduleInfoBO> list = appService.getEquipmentPlanInfo(planAssociation);
        return AjaxResult.success(list);
    }


    /**
     * 查询上传的图片
     */
    @GetMapping("/file/list")
    public AjaxResult list(WorkOrderFile workOrderFile)
    {
        String[] array = workOrderFile.getFileId().split(",");
        workOrderFile.setFileIds(array);
        List<WorkOrderFile> list = workOrderMapper.selectWorkOrderFileList(workOrderFile);
        return AjaxResult.success(list);
    }



    /**
     * 处理图片上传请求
     *
     * @param file 上传的图片文件
     * @return 上传成功后的文件信息
     */
    @PostMapping("/api/upload")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传的文件不能为空");
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 生成本地路径
//            String localPath = "/www/wwwroot/wushuichang/File/" + fileName;
            String localPath =  "F:/fctextjavaworkspace/ruoyiUpload/"+ fileName;

            WorkOrderFile workOrderFile = new WorkOrderFile();
            workOrderFile.setFilePath(localPath);
//            workOrderFile.setUploadTime(new Date());
//            workOrderFile.setCreatedAt(new Date());

            // 确保文件保存路径存在
//            File directory = new File("/www/wwwroot/wushuichang/File/");
            File directory = new File("F:/fctextjavaworkspace/ruoyiUpload/");
            if (!directory.exists()) {
                directory.mkdirs(); // 创建路径
            }
//
//            // 插入文件上传记录到数据库
            long timestamp = System.currentTimeMillis();
            workOrderFile.setFilePath(localPath);
            workOrderFile.setFileName(fileName);
            workOrderFile.setFileId(String.valueOf(timestamp));
            workOrderMapper.insertFileUpload(workOrderFile);
            // 保存文件到服务器本地
            file.transferTo(new File(localPath));

            // 返回路径给前台页面
            return AjaxResult.success().put("filePath", localPath).put("fileName", fileName).put("size", file.getSize())
                    .put("fileId", String.valueOf(timestamp))
                    ;
        } catch (Exception e) {
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/createWorkOrder")
    public String createWorkOrder(@RequestBody WorkOrderVO workOrderVO) {
        // 这里可以进行业务处理、保存数据库等
        workOrderService.createWorkOrder( workOrderVO);
        return "工单已接收!";
    }
    @PostMapping("/createSfile")
    public String createSfile(@RequestBody ScheduleFile scheduleFile) {
        // 这里可以进行业务处理、保存数据库等
        List<ScheduleFile> files=new ArrayList<ScheduleFile>();
        for(int i = 0; i < scheduleFile.getImages().length; i++) {
            ScheduleFile s=new ScheduleFile();
            s=scheduleFile;
            s.setFilePath(scheduleFile.getImages()[i]);
            workOrderMapper.insertSfile(s);
        }
        return "工单已接收!";
    }

    @PostMapping("/question")
    public String Question( @RequestBody Question question) {
        String result = getAppQuestion(question.getQuestion(), question.getScheme());
        // 按照句号等标记符号分割回复，同时插入换行符
        return result.replaceAll("，", "，\n")
                .replaceAll("。", "。\n")
                .replaceAll("；", "；\n");

    }

    public static String appCall( String question, String scheme) throws ApiException, NoApiKeyException, InputRequiredException {
        String AppId = "";
        // String ApiKey = "sk-a079a532f4aa4dc3b834c04911b09e04";  // 苏区云助手apiKey
        String ApiKey = "sk-4a02a0310efa44488a54a65e0ed11af7 "; //sk-4a02a0310efa44488a54a65e0ed11af7  污水厂apikey
        if ("0".equals(scheme)){ //环评问题
            AppId = "0ae7a6b3e86c4b6b8f491fc2ab948a3a";
        }else if ("1".equals(scheme)){ //许可问题
            AppId = "402bb387da5b4dc38df00ad35b784982";
        }else if ("2".equals(scheme)){//环评许可问题
            AppId = "710518c65e824fd7b79a3c6015f6368a";
        }else if ("3".equals(scheme)){//环评深度思考(deepseek+知识库)
            AppId = "50ee22e5cec948abb1da89375b40cfb3";
        }else if ("4".equals(scheme)){//许可深度思考(deepseek+知识库)
            AppId = "a3165d070ed54d5da4fa358aadc91566";
        }else if ("5".equals(scheme)){//深度思考(deepseek)
            AppId = "8129eb4c13b34da3aefe75bccb00beb4";
        }else if ("6".equals(scheme)){//行政许可办理事项
            AppId = "e1b9a7ee1c344fb2bdde828473beec56";
        }else{ //其他问题 无ai知识库
            AppId = "45716246f8ff4e908f5bf28e20222118";
        }
        AppId = "fccd319e3940435196455ba3f72cea80";

        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey(ApiKey)// 百炼API Key
                .appId(AppId)// 百炼大模型APPID
                .prompt(question)
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("text: %s\n",
                result.getOutput().getText());
        return result.getOutput().getText();
    }


    // 调用阿里云机器人API 阿里云百炼大模型附带自己的知识库，可以根据自己的业务场景定制模型。
    public String getAppQuestion(String question, String scheme) {
        try {
            String result = appCall(question,scheme);
            return result;
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("message："+e.getMessage());
            System.out.println("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
            return e.getMessage();
        }

    }







}
